class Image < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
  belongs_to :image_status
  
  belongs_to :article
  # after_save :upload_image
  
  def self.upload_image
    return nil
  end
  
  # Generate thumbnail from the original image
  def thumbnail!(w, h)
    ImageTools.thumbnail(full_path, image_path(w,h), w.to_i, h.to_i)
  end
  
  def upload(pic)
    #Update @image.picture 

    @file_path = "upload/images/event/#{self.id.to_s + "_" + pic.original_filename}"
    File.open(@file_path, "wb") { |f| f.write(pic.read) }
    
    #create thumbnails
    createThumbnails
    
    self.width = ImageTools.getWidth(@file_path)
    self.height = ImageTools.getHeight(@file_path)
    self.image_type = ImageTools.getType(@file_path)
    
    self.save
  end
  
  def createThumbnails
    @file_path = "upload/images/event/#{self.id.to_s + "_" + self.picture}"
    # create thumbnail
    @thumbs = Thumbnail.all
    
    @thumbs.each do |item|
      ImageTools.createThumbnail(@file_path, "upload/images/event/thumbnails/#{self.id.to_s + "_" + item.width.to_s + "x" + item.height.to_s + "_" + self.picture}", item.width.to_i, item.height.to_i == 0 ? nil : item.height.to_i)
    end
  end
  
  def deleteThumbnails
    Dir.foreach("upload/images/event/thumbnails"){|x| File.delete("upload/images/event/thumbnails/"+x)  if x=~/^#{self.id.to_s}(.*)/ }
  end
  
  def deleteImage
    @file_path = "upload/images/event/#{self.id.to_s + "_" + self.picture}"
    File.delete(@file_path) if File.exist?(@file_path)
    deleteThumbnails
  end
  
  def renderImage
    "upload/images/event/#{self.id.to_s + "_" + self.picture}"
  end

  def renderThumbnail(size = "small")
    @thumb = Thumbnail.get(size)
    
    "upload/images/event/thumbnails/#{self.id.to_s + "_" + @thumb.width.to_s + "x" + @thumb.height.to_s + "_" + self.picture}"
  end
  
  def self.reporter_images_list(user, filters = {})
	@where = "user_id = '#{ user.id }' AND"

	if filters[:text] && !filters[:text].empty?
		@where += " (title LIKE '%#{ filters[:text] }%' OR" +
					" body LIKE '%#{ filters[:text] }%'" +					
					") AND"
	end
	
	if !@where.empty?
		@where += " 1=1"
	end
	
	self.find(:all, :order => "images.updated_at DESC", :conditions => @where)
  end
  
end
